package cn.xf.districonfig.client.register;

import cn.xf.districonfig.client.annotation.EnableConfigClient;
import cn.xf.districonfig.client.processor.SpringValueProcessor;
import cn.xf.districonfig.client.rpc.RpcEnvCache;
import cn.xf.districonfig.client.scope.RefreshScopeRegistry;
import cn.xf.districonfig.client.scope.XfPropertyPlaceholderConfigurer;
import cn.xf.districonfig.client.util.BeanRegistar;
import cn.xf.districonfig.client.util.PlaceHolderHelper;
import cn.xf.districonfig.client.zk.CuratorUtil;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Map;

public class ConfigClientRegistar implements ImportBeanDefinitionRegistrar, EnvironmentAware {

    private Environment environment;

    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {

        Map<String, Object> annotationAttributes = metadata.getAnnotationAttributes(EnableConfigClient.class.getName(), true);
        assert annotationAttributes != null;
        Object mode = annotationAttributes.get("mode");

        BeanRegistar.registerBean(registry, PlaceHolderHelper.class.getName(), null, PlaceHolderHelper.class);
        BeanRegistar.registerBean(registry, SpringValueRegistry.class.getName(), null, SpringValueRegistry.class);
        BeanRegistar.registerBean(registry, SpringValueProcessor.class.getName(), null, SpringValueProcessor.class);
        if ("rpc".equalsIgnoreCase(mode.toString())) {
            registRpcConfig(registry);
        } else if("redis".equalsIgnoreCase(mode.toString())) {
            registRedisConfig(registry);
        } else if("zk".equalsIgnoreCase(mode.toString()) || "zookeeper".equalsIgnoreCase(mode.toString())) {
            registZkConfig(registry);
        }
        BeanRegistar.registerBean(registry, XfPropertyPlaceholderConfigurer.class.getName(), null,
                XfPropertyPlaceholderConfigurer.class);
    }

    private void registZkConfig(BeanDefinitionRegistry registry) {
        BeanRegistar.registerBean(registry, "refreshScopeRegistry", null, RefreshScopeRegistry.class);
        BeanRegistar.registerBean(registry, "curatorUtil", null, CuratorUtil.class);
    }

    private void registRedisConfig(BeanDefinitionRegistry registry) {
    }

    private void registRpcConfig(BeanDefinitionRegistry registry) {

        BeanRegistar.registerBean(registry, "rpcEnvCache", null, RpcEnvCache.class);
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}
